package com.autolinq.servlet;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

import com.autolinq.service.ServiceHandler;
import com.autolinq.util.image.ImageUtils;
import com.autolinq.util.qrcode.QRCode;

public class JSONServlet extends AbstractDPCAServlet {
	Logger logger = Logger.getLogger(this.getClass().getName());
	private static final String UPLOAD_PATH = "qrcode"
			+ System.getProperty("file.separator");

	public void doGet(HttpServletRequest request, HttpServletResponse response)

	throws ServletException, IOException {

		doPost(request, response);

	}
	
	@Override
    public void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws javax.servlet.ServletException, java.io.IOException {
        if(null == servletRequest.getParameter("numChunks")){
            doPost(servletRequest, servletResponse);
        }else{
            doGet(servletRequest, servletResponse);
        }
    }
	
	public static byte[] readStream(InputStream inStream) throws Exception {  
	    ByteArrayOutputStream outSteam = new ByteArrayOutputStream();  
	    byte[] buffer = new byte[10240];  
	    int len = -1;  
	    while ((len = inStream.read(buffer)) != -1) {  
	    	System.out.println("len=="+len); 
	        outSteam.write(buffer, 0, len);  
	    }  
	    outSteam.close();  
	    inStream.close();  
	    return outSteam.toByteArray();  
	}  
	/**
	 * 
	 * Web Server 所有接口入口
	 */

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.debug("root");
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String TOKEN = "autolinkq";// Token
		System.out.println("ssssdddd");
		String rootPath = request.getRealPath("/");

		String qrcodePath = rootPath + System.getProperty("file.separator")
				+ UPLOAD_PATH + System.getProperty("file.separator");

		String deviceId = request.getParameter("deviceId");
		String actionType = request.getParameter("actionType");
		

		

        
		if ("regDevice".equals(actionType)) {
			if (deviceId != null && deviceId.length() == 16) {
				try {

					String regURL = prop.getProperty("regURL");
					String filePostfix="png";
					String fileName = qrcodePath+"oauth_QR_CODE_"+deviceId+"."+filePostfix;
					boolean flag = ImageUtils.createImgFromURL(regURL+deviceId+".png", fileName);
					
					String message = "";
					if(flag){
						QRCode qrcode = new QRCode();
						File file = new File(fileName);
						String qrcodeUrl = qrcode.decode(file);
						//response.sendRedirect("weixin://qr/AQD-vcCODBfoVKzXeLAQrBz2Ktyp_OeWwvVoTkMa");
						message = "{errcode:0,errmesage:\"\",qrcode:\""+"qrcode/"+"oauth_QR_CODE_"+deviceId+"."+filePostfix+"\",qrcodeURL:\""+qrcodeUrl+"\"}";
					}else{
						message = "{errcode:2,errmesage:\"deviceId is not in the db.\"}";
					}
					
	        		printMessageSave(request,response,message);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}   
			} else {
				String message = "{errcode:1,errmesage:\"deviceId length invalid.\"}";
	    		printMessageSave(request,response,message);
			}
		}else{
			String requestMsg = "";;
			try {
				requestMsg = unmarshalFromJSONStream(request.getInputStream());
			} catch (Exception e) {
				e.printStackTrace();
			}
			
    		printMessageSave(request,response,ServiceHandler.handle(requestMsg, prop));
		}

	}
	
	private void printMessageSave(HttpServletRequest request,
			HttpServletResponse response, String message) throws IOException {
		response.setContentType("text/plain;charset=utf-8");
		response.setHeader("Cache-Control", "no-cache");

		PrintWriter pw = null;
		try {
			String callback = request.getParameter("callback");

			pw = response.getWriter();
			String json = "{\"portalResp\":" + message + "}";
			if (callback != null) {
				pw.write(callback + "(" + json + ")");
			} else {
				pw.write(json);
			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (pw != null) {
				pw.close();
				pw = null;
			}
		}
	}
}